package cn.zero.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.zero.config.AppConstants;
import cn.zero.model.Wallet;
import cn.zero.model.Transaction;
import cn.zero.repository.TransactionRepository;
import cn.zero.repository.WalletRepository;
import cn.zero.service.WalletService;

@Service("walletService")
public class WalletServiceImpl implements WalletService {

	@Autowired
	private WalletRepository walletRepository;
	
	@Autowired
	private TransactionRepository userAccountLogRepository;
	
	@Override
	@Transactional
	public Wallet save(Wallet wallet) {
		return walletRepository.save(wallet);
	}

	@Override
	@Transactional(readOnly = true)
	public Wallet getByUserId(Long userId) {
		return walletRepository.getByUserId(userId);
	}

	@Override
	@Transactional
	public void change(Long userId, double amount, String content) {
		Wallet wallet = getByUserId(userId);
		if (wallet == null) {
			return;
		}
		walletRepository.change(wallet.getId(), amount);
		Transaction transaction = new Transaction();
		transaction.setAmount(amount);
		transaction.setContent(content);
		transaction.setWalletId(wallet.getId());
		userAccountLogRepository.save(transaction);
		AppConstants.calculateBalance();
	}

	@Override
	@Transactional(readOnly = true)
	public double sumBalance() {
		Double sumBalance = walletRepository.sumBalance();
		return sumBalance == null ? 0 : sumBalance.doubleValue();
	}

}
